package org.jim.server.command.handler;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.packets.*;
import org.jim.core.protocol.IProtocol;
import org.jim.core.utils.JsonKit;
import org.jim.server.ImServerChannelContext;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.processor.GetGroupListCmdProcessor;
import org.jim.server.processor.group.GroupCmdProcessor;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author lml
 *
 * 获取该群组下所有成员
 */
public class UserListByGroupReqHandler extends AbstractCmdHandler {

    private static final Logger log = LoggerFactory.getLogger(UserListByGroupReqHandler.class);

    @Override
    public Command command() {
        return Command.COMMAND_GET_USER_LIST_BY_GROUP;
    }

    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {
        // 记录登录消息命令操作的日志信息

        ImServerChannelContext imServerChannelContext = (ImServerChannelContext)imChannelContext;

        UserListBody userListBody = JsonKit.toBean(imPacket.getBody(), UserListBody.class);

        // 获取登录命令处理器实例
        GroupCmdProcessor groupCmdProcessor = this.getSingleProcessor(GroupCmdProcessor.class);

        // 创建一个成功的登录响应体
        UserListResp resp = new UserListResp();

        resp.setCommand(Command.COMMAND_SUCCESS);

        // 通过处理器获取信息
        List<User> list = getList(imChannelContext, groupCmdProcessor, userListBody, resp);

        resp.setUserList(list);

        // 获取当前连接使用的协议类型
        IProtocol protocol = imServerChannelContext.getProtocolHandler().getProtocol();

        resp.setTerminal(Objects.isNull(protocol) ? Protocol.UNKNOWN : protocol.name());


        // 返回登录响应包
        return ProtocolManager.Converter.respPacket(resp, imChannelContext);
    }


    public List<User> getList(ImChannelContext imChannelContext, GroupCmdProcessor groupCmdProcessor, UserListBody userListBody, UserListResp resp) {

        if (groupCmdProcessor == null) {
            log.error("GroupCmdProcessor 未初始化或传递错误");
            return new ArrayList<>();
        }

        List<User> list = groupCmdProcessor.getUserListByGroup(userListBody, imChannelContext);
        if (Objects.isNull(list)) {
            log.error("响应处理错误！");
            /**
             * 错误回调函数
             */
            groupCmdProcessor.onFailed(imChannelContext,groupCmdProcessor,userListBody);

            List<User> lists = new ArrayList<>();

            return lists;
        }

        return list;
    }
}
